// Copyright (c) 2010 Manuel Peinado Gallego <manuel.peinado@gmail.com>
// Distributed under the MIT license


#include "stdafx.h"
#include "WorldBuilder.h"
#include "LightManager.h"

LightManager::LightManager()
{
}

size_t LightManager::getMaxNbLights() const
{
    //int result;
    //glGetIntegerv(GL_MAX_LIGHTS, &result); 
    //return result;
    return 8;
}

bool LightManager::acceptsMoreLights() const
{
    return m_registeredLights.size() < getMaxNbLights();
}

int LightManager::registerLight(ref<LightNode> light)
{
    ASSERT(acceptsMoreLights());
    ASSERT(m_registeredLights.find(light) == m_registeredLights.end());
    int maxNbLights = getMaxNbLights();

    for(int i = GL_LIGHT0; i < GL_LIGHT0 + maxNbLights; ++i)
    {
        if(m_lightIds.find(i) == m_lightIds.end())
        {
            m_registeredLights[light] = i;
            m_lightIds.insert(i);
            light->setId(i);
            return i;
        }
    }
    ASSERT(false);
    return -1;
}

// TODO don't do this on every frame, only the light position should be
// updated on every frame. The rest of the stuff should be only done
// when a light is added or removed, and only for that light
void LightManager::updateLighting()
{
    LightToId::iterator it = m_registeredLights.begin();
    for(; it != m_registeredLights.end(); ++it)
    {
        int id = it->second;
        ASSERT(id >= GL_LIGHT0 && size_t(id) < GL_LIGHT0 + getMaxNbLights());
        ref<LightNode> light = it->first;
        
        // Will only update when something has changed
        light->updateParams();
    }
}

void LightManager::clear()
{
    m_registeredLights.clear();
    m_lightIds.clear();
}